package com.storydo.file.share.project.file.entity;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import com.storydo.file.share.utils.DateUtils;

import lombok.Data;

@Data
public class Sfile implements Comparable<Sfile>{

	private String name;
	
	private String path;
	
	private Boolean isDir;
	
	private long size = 0l;
	
	private FileTime lastModify;
	
	private String humanLastModify;
	
	private String humanSize;
	
	public Sfile(Path file, Path work) {
		super();
		this.name = file.getFileName().toString();
		this.path = work.relativize(file).toString().replace("\\", "/");
		this.isDir = Files.isDirectory(file);
		try {
			this.size = Files.size(file);
			this.lastModify = Files.getLastModifiedTime(file);
			this.humanLastModify = DateUtils.formatDateTime(
				LocalDateTime.ofEpochSecond(this.lastModify.to(TimeUnit.SECONDS), 0, DateUtils.getDefaultZoneOffset()));
			this.humanSize = formateSize(this.size);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String formateSize(long size) {
		if (size >= 1000 * 1000 * 1000) {
			double d = new Long(size/1000/1000).doubleValue();
			return String.format("%.2fG", d/1000.0);
		} else if (size >= 100 * 1000 * 1000) {
			return String.format("%dM", size/1000/1000);
		} else if (size >= 1000 * 1000) {
			double d = new Long(size/1000).doubleValue();
			return String.format("%.1fM", d/1000.0);
		} else if (size > 1000) {
			return String.format("%dK", size / 1000);
		}
		return String.format("%d", size);
	}


	@Override
	public int compareTo(Sfile o) {
		int _selfType = this.isDir ? 0 : 1;
		int oType = o.isDir ? 0 : 1;
		if (_selfType != oType) {
			return _selfType - oType;
		}
		return o.lastModify.compareTo(this.lastModify);
	}
	
}
